const HOST_PORT = "52.195.139.100:8000";//"127.0.0.1:8000"; //
var client_id = Date.now().toString();
var ws_url = `ws://${HOST_PORT}/ws/${client_id}`;
var ws;

// 获取语音朗读开关
var audioControl;
// google搜索开关
var googleNewsControl;

function initWebSocket() {
    ws = new WebSocket(ws_url);
    ws.onopen = onOpen;
    ws.onclose = onClose;
    ws.onmessage = onMessage;
    ws.onerror = onError;
}

function showLoading() {
    //加载状态
    var chatContainer = document.getElementById('chat-container');
    var loadingDiv = document.createElement('div');
    loadingDiv.className = "spinner";
    loadingDiv.id = "spinner"
    loadingDiv.innerHTML = "<div class='rect1'></div><div class='rect2'></div><div class='rect3'></div><div class='rect4'></div><div class='rect5'></div>";
    chatContainer.appendChild(loadingDiv);
}
function dismissLoading() {
    var loadingDiv = document.getElementById('spinner');
    if (loadingDiv !== null) {
        var chatContainer = document.getElementById('chat-container');
        if (chatContainer.contains(loadingDiv)) {
            chatContainer.removeChild(loadingDiv);
        }
    }
}
function showError(msg) {
    dismissLoading();
    var chatContainer = document.getElementById('chat-container');
    var botMessage = document.createElement('div');
    botMessage.className = 'bot-message';
    botMessage.innerHTML = `BOT: ${msg}`;
    chatContainer.appendChild(botMessage);
    chatContainer.scrollTop = chatContainer.scrollHeight;
}

function onOpen(event) {
    document.getElementById('ws_status').innerHTML = "已连接";
    // document.getElementById("ws-id").innerHTML = client_id;
    console.log("已连接");

    showLoading();
};

function record() {
    console.log("record pressed");
}
function sendMessage() {

    var input = document.getElementById('user-input');
    var message = input.value.trim();

    if (message !== '') {
        console.log("Send: %s", message);
        flag = "0"
        if (googleNewsControl.checked) {
            flag = "1";
        }

        ws.send(`{
                    "prompt": "${message}",
                    "flag": ${flag}
                }`)

        var chatContainer = document.getElementById('chat-container');
        var userMessage = document.createElement('div');
        userMessage.className = 'user-message';
        userMessage.textContent = message;
        chatContainer.appendChild(userMessage);
        input.value = '';

        showLoading();

        chatContainer.scrollTop = chatContainer.scrollHeight;
    }
}

function onMessage(event) {
    var messages;
    var chatContainer = document.getElementById('chat-container');
    if (event.data === "heartbeat") {
        //console.log("Receive: " + event.data);
        return;
    } else {
        console.log("Receive: %s", event.data);

        var splitChar = ">*_*<";
        var origin_msg = event.data;
        var parts = origin_msg.split(splitChar);
        var content = parts[0] ?? "";
        var audioId = parts[1] ?? "";
        var botResponse = content;
        var botMessage = document.createElement('div');
        botMessage.className = 'bot-message';
        botMessage.innerHTML = "BOT: " + botResponse;
        setTimeout(() => {
            dismissLoading();

            chatContainer.appendChild(botMessage);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }, 3000);

        if (audioId.length > 0) {
            var audioButton = document.createElement('button');
            audioButton.id = audioId;
            audioButton.addEventListener('click', function () {
                playAudio(audioButton.id);
            });
            audioButton.classList.add("audio-button");
            audioButton.textContent = "朗读";
            botMessage.appendChild(audioButton);

            if (audioControl.checked) {
                // 模拟鼠标点击来实现自动播放音频
                setTimeout(() => {
                    var element = document.getElementById(audioId);
                    if (element !== null) {
                        element.click();
                    }
                }, 3000);//这里如果不加延迟，播放长音频时会出现不完整的情况
            }
        }
    }
    chatContainer.scrollTop = chatContainer.scrollHeight;
};
function playAudio(audioId) {
    var audioPlayer = document.getElementById("audio-player");
    audioPlayer.setAttribute('src', `../static/audio/${audioId}.mp3`);
    audioPlayer.addEventListener("loadeddata", function () {
        console.log("音频加载完成");
        audioPlayer.play();
    });
    // 加载音频
    audioPlayer.load();
    audioPlayer.pause();
}

function onClose(event) {
    console.log("连接已断开！");
    document.getElementById('ws_status').innerHTML = "连接已断开！";

    showError("连接已断开！");

    //5秒后重联
    console.log("连接已断开！5秒后尝试重连")
    setTimeout(initWebSocket, 5000);
}

function onError(event) {
    console.log("WebSocket Error:", event);
}

function myTask() {
    //console.log("Send: heartbeat");
    ws.send("heartbeat");
}
setInterval(myTask, 5000);

function onLoad(event) {
    // // 设置语音开关默认状态为选中
    // audioControl.checked = true;
    initWebSocket();

    googleNewsControl = document.getElementById('google-news-control');
    audioControl = document.getElementById('audio-control');
}
window.addEventListener('load', onLoad);
